/**
 * @file 支付看板
 * @author ruanairuo(ruanairuo@baijia.com)
 * @date 2020-01-19
 */
import React, {Fragment, useState, useEffect} from 'react';
import {Space, Card, Input, Row, Col} from 'antd';

import moment from 'moment';

import {
    getWindControlValues,
    fetchSearchFormOptions
} from '~/service/windControl';

import {getFirstAndLastTimestamp} from '~/utils/date';
import {numberHandle, parsePercent} from '~/utils/number';
import {convertChartListToMap} from '../../../utils/convert';

import CommonSearchBar from '../../../common/CommonSearchBar';
import EchartsLineCard from '../../../common/EchartsLineCard';
import CardTable from '../../../common/CardTable';
import PartOneTextCard from '../partOneTextCard';

import {
    searchForm,
    getDimensionId,
    pageId,
    META,
    PART_THREE_CARD_ID,
    PART_THREE_COMPOSITE_ONE_ID,
    PART_THREE_COMPOSITE_TWO_ID,
    PART_ONE_TITLE
} from './config';

const {TextArea} = Input;

const initialValues = {
    startClassTime: getFirstAndLastTimestamp({format: 'YYYY-MM-DD'})
};


const PartOne = props => {
    const {onDetail, onDownLoad, part, tooltip} = props;

    const [loading, setLoading] = useState(false);
    const [result, setResult] = useState({});
    const [selectOptions, setSelectOptions] = useState({});
    const [searchFormValues, setSearchFormValues] = useState(initialValues);
    const [drilingList, setDrilingList] = useState(null);
    const [drilingLevel, setDrilingLevel] = useState(null);

    const {
        [part]: {
            allUnitType: {
                cardList = [],
                compositeUnit = [],
                textList = [],
                simpleExcel = []
            } = {}
        } = {}
    } = result;

    const partOneCard = convertChartListToMap(cardList);
    const partOneText = convertChartListToMap(textList);
    const partOneComposite = convertChartListToMap(compositeUnit);
    const partOneExcel = convertChartListToMap(simpleExcel);

    const {
        [META[part].PART_ONE_CARD_ONE]: partOneCard1,
    } = partOneCard;

    const {
        [META[part].PART_ONE_TEXT_ONE]: partOneText1,
        [META[part].PART_ONE_TEXT_TWO]: partOneText2,
        [META[part].PART_ONE_TEXT_THREE]: partOneText3,
    } = partOneText;

    const {
        [META[part].PART_ONE_COMPOSITE_ONE]: partOneComposite1,
        [META[part].PART_ONE_COMPOSITE_TWO]: partOneComposite2
    } = partOneComposite;

    const {
        [META[part].PART_ONE_EXCEL_ONE]: partOneExcel1,
        [META[part].PART_ONE_EXCEL_TWO]: partOneExcel2
    } = partOneExcel;

    // 获取全局数据
    const getData = (params = searchFormValues) => {
        setLoading(true);

        const {startClassTime} = params;
        const [begin, end] = startClassTime || [];
        const beginRangeTime = begin && moment(begin).format('YYYY-MM-DD');
        const endRangeTime = end && moment(end).format('YYYY-MM-DD');
        params.paidDay = [beginRangeTime, endRangeTime];

        getWindControlValues({...params, part})
            .then(res => {
                const {
                    data
                } = res;

                setResult({
                    [part]: data
                });
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const handleDetail = unit => {
        const params = {
            ...searchFormValues,
            ...unit,
            drilingList: drilingList ? drilingList[part] : [],
            part
        };

        onDetail(params);
    };

    const handleDownload = unit => {
        const params = {
            ...searchFormValues,
            ...unit,
            drilingList: drilingList ? drilingList[part] : [],
            part
        };

        onDownLoad(params);
    };

    const handleBack = async params => {
        console.log('返回', params);
        const {unitId, unitName} = params;
        // 所有下钻取消
        setDrilingList({...drilingList, [part]: []});

        try {
            await getData(searchFormValues);
            // 返回搜索数据接口调用成功后level - 1
            setDrilingLevel({...drilingLevel, [part]: {unitId, level: 0}});
        }
        catch {}
    };

    const handleDrilling = async params => {
        console.log('下钻', params);
        const {unitId, unitName, info, dimension = {}} = params;

        const driling = {
            unitId,
            unitName,
            value: info.name,
            ...dimension
        };

        setDrilingList({...drilingList, [part]: [driling]});

        try {
            await getData({...searchFormValues, drilingList: [driling]});
            // 搜索接口调用成功后level + 1
            setDrilingLevel({...drilingLevel, [part]: {unitId, level: 1}});
        }
        catch {}
    };

    useEffect(() => {
        getData();
    }, [part]);

    // 表单确定
    const handleOk = fieldsValue => {
        setSearchFormValues(fieldsValue);
        setDrilingLevel(null);
        setDrilingList(null);
        getData(fieldsValue);
    };

    // 表单重置
    const handleReset = e => {
        setSearchFormValues(initialValues);
        setDrilingLevel(null);
        setDrilingList(null);
        getData(initialValues);
    };

    // 表单change
    const handleItemChange = itemKeyValue => {
        // setSearchFormValues({...searchFormValues, ...itemKeyValue});
        console.log('handleItemChange', itemKeyValue);
    };

    // 请求单个表单配置项
    const handleFetchOptions = (
        {key, searchKey, pager, dependItemKey, dependItemValue, isGetingMore, options: curOptions, fieldsValue}
    ) => {
        let permissions = searchForm.map(item => {
            if (item.key === 'startClassTime') {
                const [begin, end] = fieldsValue[item.key] || [];
                const beginRangeTime = begin && moment(begin).format('YYYY-MM-DD');
                const endRangeTime = end && moment(end).format('YYYY-MM-DD');
                const filterItems = [beginRangeTime, endRangeTime];
                const dimensionId = getDimensionId(0, 'paidDay');

                return (
                    {
                        dimensionId,
                        dimensionName: 'paidDay',
                        filterItems
                    }
                );
            }
            return (
                {
                    dimensionId: getDimensionId(0, item.key),
                    dimensionName: item.key,
                    filterItems: fieldsValue[item.key]
                }
            );
        });

        permissions = permissions.filter(item => item.filterItems?.length);

        const params = {
            pager,
            dimensionId: getDimensionId(0, key),
            dimensionName: key,
            searchKey,
            permissions,
            unitId: pageId[0].selectID
        };

        fetchSearchFormOptions(params)
            .then(res => {
                const {data, pager} = res;

                let options = data.map(item => (
                    {
                        key: item,
                        value: item,
                        label: item
                    }
                )) || [];

                // 分页时，累加展示
                if (isGetingMore) {
                    options = curOptions.concat(options);
                }

                setSelectOptions({key, options, pager});
            });
    };

    return (
        <div>
            <Card style={{marginBottom: 8}}>
                <CommonSearchBar
                    loading={loading}
                    noCache
                    config={searchForm}
                    initialValues={initialValues}
                    onOk={handleOk}
                    onReset={handleReset}
                    onItemChange={handleItemChange}
                    onfetchOptions={handleFetchOptions}
                    selectOptions={selectOptions}
                />
            </Card>
            <Card style={{width: '100%'}}>
                <Row>
                    <PartOneTextCard
                        unitId={META[part].PART_ONE_CARD_ONE}
                        unitName={partOneCard1?.unitName}
                        span={20}
                        loading={loading}
                        onDownload={handleDownload}
                        onDetail={handleDetail}
                        data={partOneCard1}
                        format={META[part].PART_ONE_CARD_ONE === PART_THREE_CARD_ID ? numberHandle : parsePercent}
                    />
                    <Col span={4}>
                        <TextArea
                            className="wind-control-text-area part-one-text-one"
                            value={partOneText1?.textContent}
                            bordered={false}
                            readOnly
                        />
                    </Col>
                </Row>
                <Row style={{marginBottom: 8}}>
                    <Col span={20}>
                        <div className="wind-control-part-one-content-right">
                            <Row>
                                <EchartsLineCard
                                    id={META[part].PART_ONE_COMPOSITE_ONE}
                                    key={META[part].PART_ONE_COMPOSITE_ONE}
                                    data={partOneComposite1}
                                    loading={loading}
                                    span={24}
                                    title={partOneComposite1?.unitName}
                                    onBack={handleBack}
                                    onDownload={handleDownload}
                                    onDetail={handleDetail}
                                    onDrilling={handleDrilling}
                                    drilingLevel={drilingLevel ? drilingLevel[part] : null}
                                    grid={{left: '10%', right: '10%', bottom: 100}}
                                    yAxisIndex={1}
                                    unitPercentIndex={META[part].PART_ONE_COMPOSITE_ONE === PART_THREE_COMPOSITE_ONE_ID
                                        ? -1 : 1}
                                    // label={{
                                    //     line: params => `${META[part].PART_ONE_COMPOSITE_ONE === PART_THREE_COMPOSITE_ONE_ID
                                    //         ? numberHandle(params.data.value, 2) : parsePercent(params.data.value, 2)}`,
                                    //     bar: params => `${numberHandle(params.data.value, 2)}`
                                    // }}
                                    xNameLength={10}
                                    tooltip={tooltip}
                                />
                                <CardTable
                                    unitId={META[part].PART_ONE_EXCEL_ONE}
                                    unitName={partOneExcel1?.unitName}
                                    onDownload={handleDownload}
                                    onDetail={handleDetail}
                                    data={partOneExcel1}
                                    loading={loading}
                                    span={24}
                                    height={300}
                                />
                            </Row>
                        </div>
                    </Col>
                    <Col span={4}>
                        <TextArea
                            className="wind-control-text-area part-one-text-two"
                            value={partOneText3?.textContent}
                            bordered={false}
                            readOnly
                        />
                    </Col>
                </Row>
                <Row>
                    <Col span={20}>
                        <div className="wind-control-part-one-content-right">
                            <Row>
                                <EchartsLineCard
                                    id={META[part].PART_ONE_COMPOSITE_TWO}
                                    key={META[part].PART_ONE_COMPOSITE_TWO}
                                    data={partOneComposite2}
                                    loading={loading}
                                    span={24}
                                    title={partOneComposite2?.unitName}
                                    onBack={handleBack}
                                    onDownload={handleDownload}
                                    onDetail={handleDetail}
                                    onDrilling={handleDrilling}
                                    drilingLevel={drilingLevel ? drilingLevel[part] : null}
                                    grid={{left: '10%', right: '10%', bottom: 100}}
                                    yAxisIndex={1}
                                    unitPercentIndex={META[part].PART_ONE_COMPOSITE_TWO === PART_THREE_COMPOSITE_TWO_ID
                                        ? -1 : 1}
                                    // label={{
                                    //     line: params => `${META[part].PART_ONE_COMPOSITE_ONE === PART_THREE_COMPOSITE_ONE_ID
                                    //         ? numberHandle(params.data.value, 2) : parsePercent(params.data.value, 2)}`,
                                    //     bar: params => `${numberHandle(params.data.value, 2)}`
                                    // }}
                                    xNameLength={10}
                                    tooltip={tooltip}
                                />
                                <CardTable
                                    unitId={META[part].PART_ONE_EXCEL_TWO}
                                    unitName={partOneExcel2?.unitName}
                                    onDownload={handleDownload}
                                    onDetail={handleDetail}
                                    data={partOneExcel2}
                                    loading={loading}
                                    span={24}
                                    height={300}
                                />
                            </Row>
                        </div>
                    </Col>
                    <Col span={4}>
                        <TextArea
                            className="wind-control-text-area part-one-text-two"
                            value={partOneText2?.textContent}
                            bordered={false}
                            readOnly
                        />
                    </Col>
                </Row>
            </Card>
        </div>
    );
};

export default PartOne;
